// Web版本的主入口文件
import { ErrorHandler } from './utils/ErrorHandler.js';
import { PerformanceUtils } from './utils/PerformanceUtils.js';
import { MainScene } from './scenes/MainScene.js';
import { ModeAScene } from './scenes/ModeAScene.js';
import { ModeBScene } from './scenes/ModeBScene.js';
import { ModeCScene } from './scenes/ModeCScene.js';

// 注册Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('./sw.js')
      .then((registration) => {
        console.log('SW registered: ', registration);
      })
      .catch((registrationError) => {
        console.log('SW registration failed: ', registrationError);
      });
  });
}

// 初始化错误处理
console.log('[INFO] ErrorHandler initialized');
ErrorHandler.init();

console.log('Starting StarDigits Jump...');
ErrorHandler.logInfo('Game initialization started');

// 性能设置（Web版本优化）
const performanceSettings = {
  animationQuality: 'medium', // Web版本使用中等质量
  particleCount: 50,
  enableShadows: false, // Web版本关闭阴影以提高性能
  enableBloom: false
};

ErrorHandler.logInfo('Performance settings', performanceSettings);

// Phaser游戏配置
const config = {
  type: Phaser.AUTO,
  width: 1280,
  height: 720,
  parent: 'game-container',
  backgroundColor: '#1a1a2e',
  scene: [ModeAScene, ModeBScene, ModeCScene, MainScene],
  scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    width: 1280,
    height: 720
  },
  render: {
    antialias: true,
    pixelArt: false,
    roundPixels: true
  },
  physics: {
    default: 'arcade',
    arcade: {
      gravity: { y: 0 },
      debug: false
    }
  },
  audio: {
    disableWebAudio: false
  }
};

// 创建游戏实例
const game = new Phaser.Game(config);
console.log('Phaser game created:', game);
ErrorHandler.logInfo('Phaser game created successfully');

// 初始化性能监控
PerformanceUtils.init();

// 游戏窗口焦点管理
window.addEventListener('focus', () => {
  if (game.scene.isActive('MainScene')) {
    game.scene.resume('MainScene');
  }
});

window.addEventListener('blur', () => {
  // Web版本不自动暂停，保持游戏运行
});

// 键盘事件处理
document.addEventListener('keydown', (event) => {
  // 防止某些按键的默认行为
  if (['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(event.code)) {
    event.preventDefault();
  }
});

// 触摸事件优化（移动设备支持）
document.addEventListener('touchstart', (e) => {
  e.preventDefault();
}, { passive: false });

document.addEventListener('touchmove', (e) => {
  e.preventDefault();
}, { passive: false });

// 窗口大小变化处理
window.addEventListener('resize', () => {
  game.scale.refresh();
});

// 导出游戏实例供调试使用
window.game = game;

console.log('星际数字跳跃 Web版本启动完成！');
